package com.ctrip.ec.biz.dao.member;
import com.ctrip.ec.dal.DaoBase;
import com.ctrip.ec.biz.entity.member.MemberAddressEntity;
import com.ctrip.ec.dal.DbAccess;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class MemberAddressDao extends DaoBase<MemberAddressEntity> {
    public MemberAddressDao() {
        super(MemberAddressEntity.class);
    }
    public MemberAddressDao(DbAccess db) {
        super(MemberAddressEntity.class,db);
    }

    public MemberAddressEntity entityByDefault(Long memberId) throws SQLException {
        String sql = "select * from " + this.getTableName() + " where member_id=? and is_default=1";
        List<MemberAddressEntity> list = this.db.query(MemberAddressEntity.class,sql,memberId);
        if(list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }

    public void clearDefault(Long memberId) throws SQLException {
        String sql = "update " + this.getTableName() + " set is_default=0 where member_id=?";
        this.db.execute(sql,memberId);
    }

    public Long getAddressCount(Long memberId) throws SQLException {
        String sql = "select count(*) from " + this.getTableName() + " where member_id=?";
        return this.db.getScalar(Long.class,sql,memberId);

    }
}
